/* (c) 2014 - 2016 Open Source Geospatial Foundation - all rights reserved
 * (c) 2001 - 2013 OpenPlans
 * This code is licensed under the GPL 2.0 license, available at the root
 * application directory.
 */
package org.geoserver.web.wicket;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.ajax.attributes.IAjaxCallListener;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.request.resource.PackageResourceReference;

/**
 * A panel which encapsulates a link containing a image and an optional label.
 *
 * @author Justin Deoliveira, OpenGeo
 */
@SuppressWarnings("serial")
public abstract class ImageAjaxLink<T> extends Panel {
    protected Image image;
    protected AjaxLink<T> link;

    /** Constructs the panel with a link containing an image. */
    public ImageAjaxLink(String id, PackageResourceReference imageRef) {
        this(id, imageRef, "");
    }

    /** Constructs the panel with a link containing an image and a label. */
    public ImageAjaxLink(String id, PackageResourceReference imageRef, String label) {
        super(id);
        link =
                new AjaxLink<T>("link") {
                    @Override
                    public void onClick(AjaxRequestTarget target) {
                        ImageAjaxLink.this.onClick(target);
                    }

                    @Override
                    protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
                        super.updateAjaxAttributes(attributes);
                        attributes
                                .getAjaxCallListeners()
                                .add(ImageAjaxLink.this.getAjaxCallListener());
                    }
                };
        add(link);
        link.add(image = new Image("image", imageRef));
        link.add(new Label("label", label));
    }

    protected IAjaxCallListener getAjaxCallListener() {
        return null;
    }

    /** Returns the image contained in this link (allows playing with its attributes) */
    public Image getImage() {
        return image;
    }

    /**
     * Returns the link wrapped by the {@link ImageAjaxLink} panel (allows playing with its
     * attributes and enable/disable the link)
     */
    public AjaxLink<T> getLink() {
        return link;
    }

    /** Handles the onClick() event generated by clicking the link. */
    protected abstract void onClick(AjaxRequestTarget target);
}
